package by.grsu.shedule;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import by.grsu.shedule.adapter.MainAdapter;
import by.grsu.shedule.api.SheduleAPI;
import by.grsu.shedule.common.BaseArrayModelFromXmlAcivity;
import by.grsu.shedule.constants.ApplicationConstants;
import by.grsu.shedule.database.SheduleManager;
import by.grsu.shedule.fragment.AboutDeveloperDialogFragment;
import by.grsu.shedule.fragment.DateFragment;
import by.grsu.shedule.model.Day;
import by.grsu.shedule.util.CalendarHelper;

import com.viewpagerindicator.TitlePageIndicator;
import com.viewpagerindicator.TitlePageIndicator.IndicatorStyle;
import com.viewpagerindicator.TitlePageIndicator.OnCenterItemClickListener;

public class MyScheduleActivity extends BaseArrayModelFromXmlAcivity<Day>
		implements OnCenterItemClickListener {

	private static final String TAG = MyScheduleActivity.class.getSimpleName();

	private MainAdapter mAdapter;

	private ViewPager mPager;

	private static MyScheduleActivity.dataChange onDataChangeListener;

	private static MyScheduleActivity.onRefreshButtonClick onRefreshButtonClick;

	private SheduleManager manager;

	private boolean isReload;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		manager = (SheduleManager) getApplicationContext().getSystemService(
				SheduleManager.SHEDULE_MANAGER);
		onDataChangeListener = new dataChange() {

			@Override
			public void onDateChangeListener() {
				SheduleAPI.refreshUrl();
				isReload = false;
				startTasks();

			}
		};

		onRefreshButtonClick = new onRefreshButtonClick() {

			@Override
			public void onRefreshButtonClickListener() {
				SheduleAPI.refreshUrl();
				isReload = true;
				startTasks();
			}
		};

	}

	@Override
	public void restoreFromDB() {
		Log.d(TAG, "restoreFromDB");
		if (mAdapter == null) {
			mAdapter = new MainAdapter(getSupportFragmentManager(),
					getApplicationContext());
			mPager = (ViewPager) findViewById(R.id.pager);
			mPager.setAdapter(mAdapter);
			mPager.setCurrentItem(CalendarHelper.getCurrentDayNumber(Calendar
					.getInstance().getTime()));
			TitlePageIndicator indicator = (TitlePageIndicator) findViewById(R.id.indicator);
			indicator.setViewPager(mPager);
			indicator.setCurrentItem(CalendarHelper
					.getCurrentDayNumber(Calendar.getInstance().getTime()));
			indicator.setFooterIndicatorStyle(IndicatorStyle.Underline);
			indicator.setOnCenterItemClickListener(this);

		} else {
			mAdapter.refreshData();
		}

	}

	@Override
	public void onCenterItemClick(int position) {
		Toast.makeText(
				this,
				CalendarHelper.convertDateForLoock(
						DateFragment.getCurrentWeek(), mPager.getCurrentItem()),
				Toast.LENGTH_SHORT).show();
	}

	@Override
	public String getUrl() {

		return SheduleAPI.getUrl();
	}

	@Override
	protected void success(List<Day> result) {
		refreshListOnDB(result, DateFragment.getCurrentWeek());
		restoreFromDB();

	}

	private void saveListToDB(List<Day> dayList, Date date) {

		List<Day> currentDayList;

		for (int i = 0; i < dayList.size(); i++) {
			currentDayList = (List<Day>) dayList.get(i);
			for (int j = 0; j < currentDayList.size(); j++) {
				manager.addNewLesson(CalendarHelper.convertDateForSearch(date,
						i), currentDayList.get(j).getSubject(), currentDayList
						.get(j).getTeacher(), currentDayList.get(j)
						.getAuditory(), currentDayList.get(j).getGroup(),
						currentDayList.get(j).getTimeStart(), currentDayList
								.get(j).getTimeFinish());
			}
		}

	}

	private void refreshListOnDB(List<Day> dayList, Date date) {
		manager.deleteLesson();
		saveListToDB(dayList, date);

	}

	@Override
	public int getLayoutResource() {
		return R.layout.main;
	}

	public static interface dataChange {
		public void onDateChangeListener();
	}

	public static MyScheduleActivity.dataChange getOnDataChangeListener() {
		return onDataChangeListener;
	}

	public static interface onRefreshButtonClick {
		public void onRefreshButtonClickListener();
	}

	public static MyScheduleActivity.onRefreshButtonClick getOnUpdateButtonClickListener() {
		return onRefreshButtonClick;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.menu, menu);

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == R.id.menu_about_developer) {
			new AboutDeveloperDialogFragment().show(
					getSupportFragmentManager(), TAG);
		}
		if (item.getItemId() == R.id.menu_settings) {
			Intent launchPreferencesIntent = new Intent(this,
					SettingsActivity.class);
			startActivityForResult(launchPreferencesIntent,
					ApplicationConstants.REQUEST_CODE_PREFERENCES);
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == ApplicationConstants.REQUEST_CODE_PREFERENCES) {
			SheduleAPI.refreshUrl();
			onRefreshButtonClick.onRefreshButtonClickListener();

		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	protected boolean isReload() {
		return isReload;
	}

	@Override
	protected void clearDataOnFragments() {
		if (mAdapter != null) {
			mAdapter.clearData();
		}
	}

}
